import * as THREE from 'three'
import { GUI } from 'three/addons/libs/lil-gui.module.min.js'

import { ColorGUIHelper } from './GUIHelper'

export const addPointLight = function ({
  scene=window.threeScene,
  color = 0xffffff,
  intensity = 1,
  distance = 1000,
  decay = 2,
  gui,
  position = [0, 10, 0],
}={}) {
  const light = new THREE.PointLight(color, intensity, distance, decay)
  light.position.set(...position)
  scene.add(light)

  if (gui) {
    const helper = new THREE.PointLightHelper(light)
    scene.add(helper)

    const updateLight = () => {
      helper.update()
    }

    const container = document.querySelector('.gui-list')
    const gui = new GUI({ title: 'point light', container })
    gui.addColor(new ColorGUIHelper(light, 'color'), 'value').name('color')
    gui.add(light, 'intensity', 0, 250, 1)
    gui.add(light, 'distance', 0, 1000).onChange(updateLight)

    const makeXYZGUI = (gui, vector3, name, onChangeFn) => {
      const folder = gui.addFolder(name)
      folder.add(vector3, 'x', -10, 10).onChange(onChangeFn)
      folder.add(vector3, 'y', 0, 10).onChange(onChangeFn)
      folder.add(vector3, 'z', -10, 10).onChange(onChangeFn)
      folder.open()
    }
    makeXYZGUI(gui, light.position, 'position')
  }

  return light
}
